package cn.genmer.test.security.algorithm.similarity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DecimalFormat;

/**
 * 文本相似度算法
 */
public class SimilarScore {

    /**日志对象*/
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public static void main(String[] args) {
        String o1 = "福建省福州市鼓楼区花园大厦";
        String o2 = "福建省福州市鼓楼区市政府";
        String o3 = "福建省福州市鼓楼区华源大厦";
        String match = "福建省福州市鼓楼区华源大厦";

        SimilarScore similarScoreTest = new SimilarScore();
        System.out.println("分值1:" + similarScoreTest.getSimilarScore(o1, match));
        System.out.println("分值2:" + similarScoreTest.getSimilarScore(o2, match));
        System.out.println("分值3:" + similarScoreTest.getSimilarScore(o3, match));
    }

    /**
     * 顺序且连续相似得分
     *
     * @param
     * @return
     * @Author Xw.H
     **/
    public double getSimilarScore(String originalAddress, String matchAddress) {


        originalAddress = replace(originalAddress);
        matchAddress = replace(matchAddress);
        int count = getSimilarScore_1(originalAddress, matchAddress);
//        int coun  = getSimilarScore_2(originalAddress, matchAddress);
//        if(logger.isDebugEnabled()){
//            System.out.println("算法一相同字符个数：" + count + "，算法二相同字符个数：" + coun);
//        }
        DecimalFormat df = new DecimalFormat("0.00");
        double v = count * 1.0 / originalAddress.length();
        String prop = df.format(v);
        Double score = Double.valueOf(prop);
        if (logger.isDebugEnabled()) {
            System.out.println("原地址：" + matchAddress);
            System.out.println("网页显示: " + ":相似得分：" + score + "，地址：" + matchAddress);
        }
        return score;
    }

    /**
     * 匹配字符串连续相似字符个数（字符截取匹配）
     *
     * @param
     * @return
     * @Author Xw.H
     **/
    private int getSimilarScore_1(String originalAddress, String matchAddress)  {
        //相似字符个数
        int count = 0;
        int len = originalAddress.length();
        String add = originalAddress;
        boolean flag = false;
        boolean fg = true;
        //原地址顺序匹配
        for (int i = 0; fg == true; flag = false) {
            for (int j = i + 1; j < len + 1; j++) {
                String s = "";
                if (j <= len) {
                    s = add.substring(i, j);
                } else {
                    fg = false;
                }
                if (matchAddress.contains(s)) {
                    flag = true;
                    if (j + 1 > len) {
                        if (s.length() >= 2) {
                            count += (s.length());
                            int indexOf = originalAddress.indexOf(s);
                            if (logger.isDebugEnabled()) {
                                System.out.println("相似字符个数【" + (s.length()) + "】，位置【" + indexOf + "," + (indexOf + j) + "】，字符【" + s.substring(0, s.length()) + "】");
                            }
                        }
                        fg = false;
                    }
                } else {
                    //最大顺序（连续）相似字符
                    if (flag) {
                        //最大顺序（连续）相似字符段 = 非相似-1
                        if (s.length() - 1 >= 2) {
                            count += (s.length() - 1);
                            int indexOf = originalAddress.indexOf(s);
                            if (logger.isDebugEnabled()) {
                                System.out.println("相似字符个数【" + (s.length() - 1) + "】，位置【" + indexOf + "," + (indexOf - 1 + j) + "】，字符【" + s.substring(0, s.length() - 1) + "】");
                            }
                        }
                        //移除相似字符
                        add = add.substring(j - 1, add.length());
                    } else {
                        //移除相似字符
                        add = add.substring(j, add.length());
                    }
                    if (add.length() < 2) {
                        //关闭循环
                        fg = false;
                    }
                    len = add.length();
                    break;
                }
            }
        }
        return count;
    }

    /**
     * 字符替换
     *
     * @param
     * @return
     * @Author Xw.H
     **/
    private String replace(String str) {
        return str.replaceAll("null", "").
                replaceAll("【", "").replaceAll("】", "")
                .replaceAll("<", "").replaceAll(">", "")
                .replaceAll("\\[", "").replaceAll("]", "")
                .replaceAll("-", "").replaceAll("\\|", "").toUpperCase();
    }

}
